package com.ctms.system.controller;

import com.ctms.common.utils.VerifyUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class IdentifyingController {

    @RequestMapping(value = "/getImg",method = {RequestMethod.POST ,RequestMethod.GET })
    protected void createImg(HttpServletRequest req, HttpServletResponse res) throws Exception{
        //1、生成随机的验证码及图片
        Object[] objects = VerifyUtil.createImage();
        //2、将验证码存入session
        String imgCode = (String) objects[0];
        HttpSession session = req.getSession();
        session.setAttribute("imgCode",imgCode);
        //3、将图片输出给浏览器
        BufferedImage img = (BufferedImage) objects[1];
        res.setContentType("image/png");
        //服务器自动创建输出流，目标指向浏览器
        OutputStream os = res.getOutputStream();
        ImageIO.write(img,"png",os);
        os.close();
    }

    /**
     * 校验验证码
     */
    @PostMapping("/checkVerify")
    @ResponseBody
    public String checkVerify(String verifyCode, HttpSession session) {
        String result = "";
        try{
            String inputStr = verifyCode;
            //从session中获取随机数
            String imgCode = (String) session.getAttribute("imgCode");
            if (imgCode == null) {
                result = "false";
                return result;
            }
            if (imgCode.equals(inputStr)) {
                result = "true";
                return result;
            } else {
                result = "false";
                return result;
            }
        }catch (Exception e){
             result = "false";
             return result;
        }
    }

}
